﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Text;


namespace Baidu
{
    public class BaiduPush
    {
        // 百度云推送 API:
        // http://developer.baidu.com/wiki/index.php?title=docs/cplat/push/api/list#push_msg

        private const string kPushURL = "https://channel.api.duapp.com/rest/2.0/channel/channel";
        private const string kHttpMethod = "POST";
        private const int kRespMaxKB = 2; //in KB



        private static string CalcSign(Dictionary<string, string> paramDict, string secret_key)
        {
            SortedDictionary<string, string> sortDict = new SortedDictionary<string, string>(paramDict);
            sortDict.Remove("sign");//計算sign時，不能包含sign參數

            string base_string = kHttpMethod + kPushURL;

            foreach (KeyValuePair<string, string> kvPair in sortDict)
            {
                base_string += string.Format("{0}={1}", kvPair.Key, kvPair.Value);
            }

            base_string += secret_key;

            base_string = Kit.ChrisKit.UrlEncodeUpper(base_string, Encoding.UTF8);
            return Kit.ChrisKit.getHashStr(base_string, Kit.HashType.MD5);
        }



        public static string PushMsg(Dictionary<string, string> paramDict, string secret_key)
        {
            paramDict["method"] = "push_msg";//推送消息
            paramDict["push_type"] = "1";    //推送類型: 1=單個人
            paramDict["message_type"] = "0"; //消息類型: 0=消息

            UInt64 unixTime = Kit.ChrisKit.ToUnixTime(DateTime.Now);
            paramDict["timestamp"] = unixTime.ToString();//用戶發起請求時的unix時間戳

            paramDict["sign"] = CalcSign(paramDict, secret_key);

            try
            {
                // Setup the request
                //
                HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(kPushURL);
                ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
                webReq.ProtocolVersion = HttpVersion.Version10;
                webReq.Method = kHttpMethod;
                webReq.Timeout = 30 * 1000;
                webReq.KeepAlive = false;
                webReq.AllowAutoRedirect = false;

                webReq.ContentType = "application/x-www-form-urlencoded; charset=utf-8";
                string postStr = Kit.ChrisKit.DictToQueryStr(paramDict, Encoding.UTF8);
                byte[] postBytes = Encoding.UTF8.GetBytes(postStr);
                webReq.ContentLength = postBytes.Length;

                using (System.IO.Stream reqStream = webReq.GetRequestStream())
                {
                    reqStream.Write(postBytes, 0, postBytes.Length);
                    reqStream.Flush();
                    reqStream.Close();
                }

                // Get the response
                //
                HttpWebResponse webResp = (HttpWebResponse)webReq.GetResponse();
                System.IO.Stream respStream = webResp.GetResponseStream();

                byte[] respBytes = new byte[kRespMaxKB * 1024];
                int bytesCount = 0;

                for (int i = 0; i < kRespMaxKB; i++)
                {
                    int readCount = respStream.Read(respBytes, bytesCount, 1024);
                    if (readCount == 0)
                        break;
                    else
                        bytesCount += readCount;
                }

                // Cleanup
                //
                respStream.Close();
                webResp.Close();

                return Encoding.UTF8.GetString(respBytes, 0, bytesCount);
            }
            catch (Exception ex)
            {
                return Kit.ChrisKit.Ex2Xml(ex, true);
            }
        }


    }
}